package memberrank

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateMemberRankLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateMemberRankLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateMemberRankLogic {
	return &BackendCreateMemberRankLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// MemberRank management
func (l *BackendCreateMemberRankLogic) BackendCreateMemberRank(in *setting.MemberRankInfo) (*setting.BaseIDResp, error) {
	logrus.Info(fmt.Sprintf("BackendCreateMemberRank MemberRankInfo: %+v", in))

	var rank model.SysMemberRank
	if in.Sort != nil {
		rank.Sort = uint16(*in.Sort)
	} else {
		rank.Sort = uint16(9999)
	}
	if in.Name != nil {
		rank.Name = strings.TrimSpace(*in.Name)

		if len(rank.Name) == 0 {
			logx.Errorw("create member rank failed, its name is required")
			return nil, errorx.NewInvalidArgumentError("setting.memberRankNameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysMemberRankColumns.Name] = map[string][]any{
			"equalTo": []any{rank.Name},
		}
		_, count, err := l.svcCtx.MemberRank.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("setting.memberRankAlreadyExists")
		}
	}
	if in.Code != nil {
		rank.Code = strings.TrimSpace(*in.Code)

		if len(rank.Code) == 0 {
			logx.Errorw("create member rank failed, its code is required")
			return nil, errorx.NewInvalidArgumentError("setting.memberRankCodeRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysMemberRankColumns.Code] = map[string][]any{
			"equalTo": []any{rank.Code},
		}
		_, count, err := l.svcCtx.MemberRank.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("setting.memberRankAlreadyExists")
		}
	}
	if in.Description != nil {
		rank.Description = strings.TrimSpace(*in.Description)
	}
	if in.Remark != nil {
		rank.Remark = strings.TrimSpace(*in.Remark)
	}
	if in.PicId != nil {
		rank.PicID = *in.PicId
	}
	if in.PicUrl != nil {
		rank.PicURL = strings.TrimSpace(*in.PicUrl)
	}
	if in.PointThreshold != nil {
		rank.PointThreshold = uint(*in.PointThreshold)
	}
	if in.IsDefault != nil {
		rank.IsDefault = uint8(*in.IsDefault)
	}
	if in.Status != nil {
		rank.Status = uint8(*in.Status)
	}
	rank.CreatedAt = time.Now()
	rank.UpdatedAt = time.Now()

	rel := &model.SysMemberRankRel{}
	if len(in.Restrictions) > 0 {
		for _, v := range in.Restrictions {
			if v.TaskId == nil || v.Threshold == nil {
				continue
			}

			var restriction model.SysMemberRankRestriction
			restriction.TaskID = *v.TaskId
			restriction.Threshhold = uint(*v.Threshold)
			if v.Sort != nil {
				restriction.Sort = uint16(*v.Sort)
			}
			if v.Status != nil {
				restriction.Status = uint8(*v.Status)
			} else {
				restriction.Status = uint8(globalkey.StatusEnabled)
			}
			rel.Restrictions = append(rel.Restrictions, &restriction)
		}
	}
	if len(in.Rules) > 0 {
		for _, v := range in.Rules {
			var rule model.SysMemberRankRule
			if v.RuleType != nil {
				rule.RuleType = uint8(*v.RuleType)
				switch rule.RuleType {
				case enum.MemberRankRuleTypeDiscount, enum.MemberRankRuleTypeGems:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)

						if v.Value != nil {
							switch rule.Mode {
							case enum.MemberRankRuleModeAmount:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.MemberRankRuleModeDiscount:
								if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 && i <= 100 {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.MemberRankRuleModeFixed:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							default:
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					}
				case enum.MemberRankRuleTypeFreeShipping:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)
					}

					if v.Regions != nil {
						rule.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
					}
				case enum.MemberRankRuleTypeExtraPoint:
					if v.Value != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.MemberRankRuleTypeCoupon:
					if v.Value != nil && v.PeriodType != nil && v.Quota != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
						rule.PeriodType = uint8(*v.PeriodType)
						rule.Quota = uint8(*v.Quota)
					}
				}
			}
			if v.Sort != nil {
				rule.Sort = uint16(*v.Sort)
			}
			if v.Status != nil {
				rule.Status = uint8(*v.Status)
			} else {
				rule.Status = uint8(globalkey.StatusEnabled)
			}
			rel.Rules = append(rel.Rules, &rule)
		}
	}
	err := l.svcCtx.MemberRank.Insert(l.ctx, nil, &rank, rel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseIDResp{
		Id:  rank.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
